// 俄罗斯方块游戏核心逻辑
const tetrisGame = {
  canvas: null,
  ctx: null,
  cellSize: 30, // 方格大小为15px
  isPaused: false,
  gameState: {
    gameOver: false,
    gameStarted: false  // 添加游戏开始状态
  },
  score: 0,
  // 游戏区域大小（以格子数为单位）
  gameWidth: 20,
  gameHeight: 20,

  // 游戏板 - 跟踪已落下的方块
  board: [],
  // 当前方块
  currentPiece: null,
  // 下一个方块
  nextPiece: null,
  currentX: 0,
  currentY: 0,
  // 游戏循环ID
  gameLoopId: null,  

  keyboardHandler: null,
  
  // 游戏速度（毫秒/帧）
  gameSpeed: 1000,
  
  // 方块颜色
  colors: [
    null,          // 0: 空
    '#FF0D72',     // 1: I 型
    '#0DC2FF',     // 2: O 型
    '#0DFF72',     // 3: T 型
    '#F538FF',     // 4: L 型
    '#FF8E0D',     // 5: J 型
    '#FFE138',     // 6: S 型
    '#3877FF'      // 7: Z 型
  ],
  
  // 方块形状定义（I, O, T, L, J, S, Z）
  shapes: [
    [],  // 空
    [[0, 0, 0, 0], [1, 1, 1, 1], [0, 0, 0, 0], [0, 0, 0, 0]],  // I
    [[1, 1], [1, 1]],  // O
    [[0, 1, 0], [1, 1, 1], [0, 0, 0]],  // T
    [[0, 0, 1], [1, 1, 1], [0, 0, 0]],  // L
    [[1, 0, 0], [1, 1, 1], [0, 0, 0]],  // J
    [[0, 1, 1], [1, 1, 0], [0, 0, 0]],  // S
    [[1, 1, 0], [0, 1, 1], [0, 0, 0]]   // Z
  ],

  // 初始化游戏
  initGame() {
    this.canvas = document.getElementById('tetrisCanvas');
    if (!this.canvas) {
      console.error('Canvas element not found');
      return;
    }

    this.ctx = this.canvas.getContext('2d');

    // 设置Canvas样式
    this.canvas.style.display = 'block';
    this.canvas.style.margin = '0 auto';

    // 初始化游戏板
    this.initBoard();
    
    // 设置Canvas大小
    this.resizeCanvas();
    window.addEventListener('resize', () => this.resizeCanvas());

    // 初始化游戏状态
    this.isPaused = false;
    this.gameState.gameOver = false;
    this.gameState.gameStarted = false;  // 游戏未开始
    this.score = 0;
    
    // 设置键盘控制
    this.setupKeyboardControls();
  },
  // 添加开始游戏方法
  startGame() {
    if (this.gameState.gameStarted) return;  // 防止重复调用
    
    this.gameState.gameStarted = true;
    
    // 确保有一个下一个方块
    if (!this.nextPiece) {
      this.generateNextPiece();
    }
    
    // 生成第一个方块
    this.createNewPiece();
    
    // 启动游戏循环
    this.startGameLoop();
  },
  // 生成下一个方块
  generateNextPiece() {
    const nextType = Math.floor(Math.random() * 7) + 1;
    this.nextPiece = this.shapes[nextType];
  },
  // 初始化游戏板
  initBoard() {
    this.board = [];
    for (let y = 0; y < this.gameHeight; y++) {
      this.board[y] = [];
      for (let x = 0; x < this.gameWidth; x++) {
        this.board[y][x] = 0;
      }
    }
  },
  // 启动游戏循环
  startGameLoop() {
    if (this.gameLoopId) {
      clearInterval(this.gameLoopId);
    }
    
    this.gameLoopId = setInterval(() => {
      if (!this.isPaused && !this.gameState.gameOver) {
        this.moveDown();
      }
    }, this.gameSpeed);
  },
  // 修改 setupKeyboardControls 方法
  setupKeyboardControls() {
    // 保存键盘事件处理函数的引用，以便能够移除它
    this.keyboardHandler = (e) => {
      // 如果游戏未开始，只响应 R 键
      if (!this.gameState.gameStarted) {
        if (e.key === 'r' || e.key === 'R') {
          this.startGame();
        }
        return;
      }
      
      if (this.gameState.gameOver) {
        if (e.key === 'r' || e.key === 'R') {
          this.restartGame();
        }
        return;
      }

      switch (e.key) {
        case 'ArrowLeft':
          this.moveLeft();
          break;
        case 'ArrowRight':
          this.moveRight();
          break;
        case 'ArrowDown':
          this.moveDown();
          break;
        case 'ArrowUp':
          this.rotatePiece();
          break;
        case ' ': // 空格键
          this.dropDown();
          break;
        case 'p':
        case 'P':
          this.togglePause();
          break;
        case 'r':
        case 'R':
          this.restartGame();
          break;
      }
    };
    
    document.addEventListener('keydown', this.keyboardHandler);
  },
  // 左移方块
  moveLeft() {
    if (!this.checkCollision(-1, 0)) {
      this.currentX--;
      this.drawGrid();
      this.drawPiece();
    }
  },
  // 右移方块
  moveRight() {
    if (!this.checkCollision(1, 0)) {
      this.currentX++;
      this.drawGrid();
      this.drawPiece();
    }
  },
  // 下移方块
  moveDown() {
    if (!this.checkCollision(0, 1)) {
      this.currentY++;
      this.drawGrid();
      this.drawPiece();
    } else {
      // 方块落地，固定到游戏板
      this.lockPiece();
      // 检查是否有完整行
      const linesCleared = this.clearLines();
      // 增加分数
      this.updateScore(linesCleared);
      // 生成新方块
      this.createNewPiece();
    }
  },
  // 快速下落
  dropDown() {
    // 立即计算方块的最终位置
    let dropY = this.currentY;
    while (!this.checkCollision(0, dropY - this.currentY + 1)) {
      dropY++;
    }
    
    // 更新方块位置
    this.currentY = dropY;
    
    // 重新绘制游戏区域
    this.drawGrid();
    this.drawPiece();
    
    // 直接锁定方块
    this.lockPiece();
    
    // 检查是否有完整行
    const linesCleared = this.clearLines();
    
    // 增加分数
    this.updateScore(linesCleared);
    
    // 生成新方块
    this.createNewPiece();
  },
  // 锁定方块到游戏板
  lockPiece() {
    for (let y = 0; y < this.currentPiece.length; y++) {
      for (let x = 0; x < this.currentPiece[y].length; x++) {
        if (this.currentPiece[y][x]) {
          const boardX = this.currentX + x;
          const boardY = this.currentY + y;
          if (boardY >= 0) {
            this.board[boardY][boardX] = this.currentPiece[y][x];
          }
        }
      }
    }
  },
  // 清除完整行
  clearLines() {
    let linesCleared = 0;
    for (let y = this.gameHeight - 1; y >= 0; y--) {
      let isLineComplete = true;
      for (let x = 0; x < this.gameWidth; x++) {
        if (this.board[y][x] === 0) {
          isLineComplete = false;
          break;
        }
      }

      if (isLineComplete) {
        // 添加消除动画效果
        // 将完整行设置为白色，表示即将消除
        for (let x = 0; x < this.gameWidth; x++) {
          this.board[y][x] = 0;
        }
        
        // 立即重新绘制网格以显示消除效果
        this.drawGrid();
        
        // 移除完整行
        this.board.splice(y, 1);
        // 在顶部添加空行
        this.board.unshift(Array(this.gameWidth).fill(0));
        // 重新检查当前行（因为移除后行索引变化）
        y++;
        linesCleared++;
      }
    }
    return linesCleared;
  },
  // 更新分数
  updateScore(linesCleared) {
    switch (linesCleared) {
      case 1:
        this.score += 100;
        break;
      case 2:
        this.score += 300;
        break;
      case 3:
        this.score += 500;
        break;
      case 4:
        this.score += 800;
        break;
    }
  },
  // 暂停/继续游戏
  togglePause() {
    this.isPaused = !this.isPaused;
  },
  // 重新开始游戏
  restartGame() {
    this.initBoard();
    this.isPaused = false;
    this.gameState.gameOver = false;
    this.score = 0;
    this.createNewPiece();
    this.startGameLoop();
  },
  // 生成新方块
  createNewPiece() {
    // 如果还没有下一个方块，生成一个
    if (!this.nextPiece) {
      this.generateNextPiece();
    }
    
    // 使用下一个方块作为当前方块
    this.currentPiece = this.nextPiece;
    
    // 生成新的下一个方块
    this.generateNextPiece();
    
    // 设置初始位置（居中）
    this.currentX = Math.floor((this.gameWidth - this.currentPiece[0].length) / 2);
    this.currentY = 0;
    
    // 检查游戏是否结束
    if (this.checkCollision(0, 0)) {
      this.gameState.gameOver = true;
    }
    
    // 绘制方块
    this.drawPiece();
  },
  // 获取下一个方块（供Vue组件显示）
  getNextPiece() {
    // 如果还没有下一个方块，生成一个
    if (!this.nextPiece) {
      const nextType = Math.floor(Math.random() * 7) + 1;
      this.nextPiece = this.shapes[nextType];
    }
    return this.nextPiece;
  },
  // 检查碰撞
  checkCollision(offsetX, offsetY) {
    for (let y = 0; y < this.currentPiece.length; y++) {
      for (let x = 0; x < this.currentPiece[y].length; x++) {
        if (this.currentPiece[y][x]) {
          const newX = this.currentX + x + offsetX;
          const newY = this.currentY + y + offsetY;
          
          // 检查是否超出边界或与已有方块碰撞
          if (
            newX < 0 ||
            newX >= this.gameWidth ||
            newY >= this.gameHeight ||
            (newY >= 0 && this.board[newY][newX])
          ) {
            return true;
          }
        }
      }
    }
    return false;
  },
  // 旋转方块
  rotatePiece() {
    // 创建旋转后的新矩阵
    const rotated = [];
    for (let i = 0; i < this.currentPiece[0].length; i++) {
      rotated.push([]);
      for (let j = this.currentPiece.length - 1; j >= 0; j--) {
        rotated[i].push(this.currentPiece[j][i]);
      }
    }
    
    // 保存当前形状
    const oldPiece = this.currentPiece;
    
    // 尝试旋转
    this.currentPiece = rotated;
    
    // 如果旋转后发生碰撞，则恢复原形状
    if (this.checkCollision(0, 0)) {
      this.currentPiece = oldPiece;
    } else {
      // 重新绘制
      this.drawGrid();
      this.drawPiece();
    }
  },
  // 绘制当前方块
  drawPiece() {
    for (let y = 0; y < this.currentPiece.length; y++) {
      for (let x = 0; x < this.currentPiece[y].length; x++) {
        if (this.currentPiece[y][x]) {
          this.ctx.fillStyle = this.colors[this.currentPiece[y][x]];
          this.ctx.fillRect(
            (this.currentX + x) * this.cellSize,
            (this.currentY + y) * this.cellSize,
            this.cellSize, this.cellSize
          );
          // 绘制边框
          this.ctx.strokeStyle = 'white';
          this.ctx.strokeRect(
            (this.currentX + x) * this.cellSize,
            (this.currentY + y) * this.cellSize,
            this.cellSize, this.cellSize
          );
        }
      }
    }
  },
  // 调整Canvas大小
  resizeCanvas() {
    // 计算游戏区域的像素大小
    const pixelWidth = this.gameWidth * this.cellSize;
    const pixelHeight = this.gameHeight * this.cellSize;

    // 设置Canvas大小
    this.canvas.width = pixelWidth;
    this.canvas.height = pixelHeight;

    // 重新绘制网格
    this.drawGrid();
  },
  // 绘制游戏网格背景
  drawGrid() {
    if (!this.ctx) return;

    const { width, height } = this.canvas;
    const { cellSize } = this;

    // 清空画布
    this.ctx.fillStyle = '#272626';
    this.ctx.fillRect(0, 0, width, height);

    // 绘制已锁定的方块
    if (this.board && this.board.length > 0) {
      for (let y = 0; y < this.gameHeight; y++) {
        for (let x = 0; x < this.gameWidth; x++) {
          if (this.board[y] && this.board[y][x]) {
            this.ctx.fillStyle = this.colors[this.board[y][x]];
            this.ctx.fillRect(x * cellSize, y * cellSize, cellSize, cellSize);
            // 绘制边框
            this.ctx.strokeStyle = 'white';
            this.ctx.strokeRect(x * cellSize, y * cellSize, cellSize, cellSize);
          }
        }
      }
    }

    // 设置网格颜色
    this.ctx.strokeStyle = 'rgba(0, 0, 0, 0.3)';
    this.ctx.lineWidth = 1;

    // 绘制垂直线
    for (let x = 0; x <= width; x += cellSize) {
      this.ctx.beginPath();
      this.ctx.moveTo(x, 0);
      this.ctx.lineTo(x, height);
      this.ctx.stroke();
    }

    // 绘制水平线
    for (let y = 0; y <= height; y += cellSize) {
      this.ctx.beginPath();
      this.ctx.moveTo(0, y);
      this.ctx.lineTo(width, y);
      this.ctx.stroke();
    }
  },
  // 清理游戏资源
  cleanup() {
    window.removeEventListener('resize', () => this.resizeCanvas());
    this.canvas = null;
    this.ctx = null;
  },
  // 修改 resetGame 方法
  resetGame() {
    // 清理现有的游戏循环
    if (this.gameLoopId) {
      clearInterval(this.gameLoopId);
      this.gameLoopId = null;
    }
    
    // 移除键盘事件监听器
    if (this.keyboardHandler) {
      document.removeEventListener('keydown', this.keyboardHandler);
      this.keyboardHandler = null;
    }
    
    // 重置游戏状态
    this.isPaused = false;
    this.gameState.gameOver = false;
    this.gameState.gameStarted = false;  // 游戏未开始
    this.score = 0;
    
    // 重置方块
    this.currentPiece = null;
    this.nextPiece = null;
    this.currentX = 0;
    this.currentY = 0;
    
    // 重新初始化游戏板
    this.initBoard();
    
    // 重新绘制网格
    this.drawGrid();
  }
};

export default tetrisGame;